package com.bjb.vr.common.service;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bjb.vr.common.ao.ResFavoriteAo;
import com.bjb.vr.common.constant.ThreadLocalConstant;
import com.bjb.vr.common.dto.*;
import com.bjb.vr.common.mapper.ResFavoritesMapper;
import com.bjb.vr.common.result.CommonResult;
import com.bjb.vr.common.utils.DateTimeUtil;
import com.bjb.vr.common.utils.GuavaCacheUtil;
import com.bjb.vr.common.utils.ThreadLocalUtil;
import com.bjb.vr.common.vo.ResFavoriteVo;
import com.bjb.vr.common.vo.UmsAccountVo;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @author admin
 * @description 针对表【res_favorites】的数据库操作Service实现
 * @createDate 2022-03-18 18:00:07
 */
@Service
public class ResFavoritesService extends ServiceImpl<ResFavoritesMapper, ResFavorites> {

    @Autowired
    UmsAccountService umsAccountService;

    @Autowired
    ResPlatformResourceService platformResourceService;

    @Autowired
    ResLocalResourceService localResourceService;

    @Autowired
    ResFavoritesMapper resFavoritesMapper;

    @Autowired
    ResContentService resContentService;

    @Resource
    FileOperationService fileOperationService;

    /**
     * 添加到收藏夹
     *
     * @param resFavoriteAo
     * @return
     */
    public boolean addFavorite(ResFavoriteAo resFavoriteAo) {
        GuavaCacheUtil.getFavoritesCache().invalidateAll();
        // 查询用户信息
        UmsAccountVo umsAccountVo = (UmsAccountVo) ThreadLocalUtil.get(ThreadLocalConstant.USER_ACCOUNT_INFO);
        // 添加到我的收藏列表
        List<ResFavorites> favorites = new ArrayList<>(resFavoriteAo.getResIds().size());
        resFavoriteAo.getResIds().forEach(resId -> {
            ResFavorites favorite = new ResFavorites();
            favorite.setAccountId(umsAccountVo.getUserId());
            favorite.setResId(resId);
            favorites.add(favorite);
        });
        return saveBatch(favorites);
    }

    /**
     * 从收藏夹删除
     *
     * @param resFavoriteAo
     * @return
     */
    public boolean removeFavorite(ResFavoriteAo resFavoriteAo) {
        GuavaCacheUtil.getFavoritesCache().invalidateAll();
        return this.removeByIds(resFavoriteAo.getIds());
    }

    /**
     * 根据条件查询收藏夹
     *
     * @param resFavoriteAo
     * @return
     */
    public CommonResult queryFavorite(ResFavoriteAo resFavoriteAo) {
        SysPlatform sysPlatform = (SysPlatform) ThreadLocalUtil.get(ThreadLocalConstant.USER_PLATFORM_INFO);
        // 查询用户信息
        UmsAccountVo umsAccountVo = (UmsAccountVo) ThreadLocalUtil.get(ThreadLocalConstant.USER_ACCOUNT_INFO);
        // 构造查询条件
        MPJLambdaWrapper<ResFavoriteVo> joinQueryWrapper = new MPJLambdaWrapper<>();
        joinQueryWrapper.select(ResFavorites::getId)
                .select(ResFavorites::getResId)
                .select(ResFavorites::getAccountId)
                .select(ResLocalResource::getResName)
                .select(ResLocalResource::getResType)
                .select(ResLocalResource::getPeriod)
                .select(ResLocalResource::getLevel)
                .select(ResLocalResource::getSubject)
                .select(ResLocalResource::getThemeCode)
                .select(ResContentAuthority::getContValidStartDate)
                .select(ResContentAuthority::getContValidEndDate)
                .selectAs(ResLocalResource::getContentSize, "capacity")
                .leftJoin(ResLocalResource.class, ResLocalResource::getResId, ResFavorites::getResId)
                .innerJoin(ResContentAuthority.class, on -> on.eq(ResContentAuthority::getContentId, ResLocalResource::getResId).eq(ResContentAuthority::getTenantId, umsAccountVo.getTenantId()));
        if (Objects.isNull(resFavoriteAo.getAccountId())) {
            joinQueryWrapper.eq(ResFavorites::getAccountId, umsAccountVo.getUserId());
        } else {
            joinQueryWrapper.eq(ResFavorites::getAccountId, resFavoriteAo.getAccountId());
        }
        joinQueryWrapper.eq(Objects.nonNull(sysPlatform.getPlatformCode()), ResLocalResource::getThemeCode, sysPlatform.getPlatformCode());
        joinQueryWrapper.eq(Objects.nonNull(resFavoriteAo.getPeriod()), ResLocalResource::getPeriod, resFavoriteAo.getPeriod());
        joinQueryWrapper.eq(Objects.nonNull(resFavoriteAo.getLevel()), ResLocalResource::getLevel, resFavoriteAo.getLevel());
        joinQueryWrapper.eq(Objects.nonNull(resFavoriteAo.getSubject()), ResLocalResource::getSubject, resFavoriteAo.getSubject());
        joinQueryWrapper.eq(Objects.nonNull(resFavoriteAo.getResType()), ResLocalResource::getResType, resFavoriteAo.getResType());
        joinQueryWrapper.like(Objects.nonNull(resFavoriteAo.getResName()), ResLocalResource::getResName, resFavoriteAo.getResName());
        // 执行查询
        IPage<ResFavoriteVo> joinPage = resFavoritesMapper.selectJoinPage(new Page<>(resFavoriteAo.getCurrent(), resFavoriteAo.getSize()), ResFavoriteVo.class, joinQueryWrapper);
        buildNeedInfo(joinPage.getRecords());
        return CommonResult.Ok().setResult(joinPage);
    }

    /**
     * 构建需要的信息
     *
     * @param resFavoriteVos
     * @return
     */
    private void buildNeedInfo(List<ResFavoriteVo> resFavoriteVos) {
        for (ResFavoriteVo resFavoriteVo : resFavoriteVos) {
            ResPlatformResource platformResource = platformResourceService.getByResId(resFavoriteVo.getResId());
            if (Objects.isNull(platformResource)){
                continue;
            }
            // 设置预览图地址
            resFavoriteVo.setPreImagePath(platformResource.getPreImagePath());
            // 设置字典值
            if (StringUtils.isNotBlank(resFavoriteVo.getPreImagePath())){
                resFavoriteVo.setPreImagePath(fileOperationService.downloadFile(resFavoriteVo.getPreImagePath()));
            }
            // 设置资源权限
//            if (resFavoriteVo.getContValidStartDate() == null && resFavoriteVo.getContValidEndDate() == null) {
//                resFavoriteVo.setContentValidState(1);
//            } else {
//                LocalDate nowDate = DateTimeUtil.getLocalDate(new Date());
////                if (nowDate.compareTo(resFavoriteVo.getContValidStartDate()) >= 0 && nowDate.compareTo(resFavoriteVo.getContValidEndDate()) <= 0) {
//                if (nowDate.compareTo(resFavoriteVo.getContValidStartDate()) >= 0 ) {
//                    resFavoriteVo.setContentValidState(1);
//                } else {
//                    resFavoriteVo.setContentValidState(2);
//                }
//            }
            LocalDate nowDate = DateTimeUtil.getLocalDate(new Date());
            if (resFavoriteVo.getContValidStartDate() == null){
                resFavoriteVo.setContentValidState(2);
            }
            else if (resFavoriteVo.getContValidEndDate() == null) {
                if (nowDate.compareTo(resFavoriteVo.getContValidStartDate()) >= 0 ) {
                    resFavoriteVo.setContentValidState(1);
                } else {
                    resFavoriteVo.setContentValidState(2);
                }
            } else {
                if (nowDate.compareTo(resFavoriteVo.getContValidStartDate()) >= 0 && nowDate.compareTo(resFavoriteVo.getContValidEndDate()) <= 0) {
                    resFavoriteVo.setContentValidState(1);
                } else {
                    resFavoriteVo.setContentValidState(2);
                }
            }
        }
    }
}




